const { StudyProgress, User } = require('../models');
const { Op } = require('sequelize');

// 初始化学习计划数据
const studyPlanData = [
  // 第一阶段：Web 技术基础（HTML/CSS/JavaScript）
  { stage: 1, day: 1, title: 'HTML 入门：标签、结构、常用元素（head/body/div/p/h1等）', homework: '创建一个简单的个人介绍页面' },
  { stage: 1, day: 2, title: 'HTML 表单与输入控件', homework: '制作一个注册表单' },
  { stage: 1, day: 3, title: 'CSS 基础：选择器、颜色、字体、背景', homework: '给之前的页面添加样式' },
  { stage: 1, day: 4, title: 'CSS 盒模型、布局方式（flex/grid）', homework: '使用 flex 布局制作响应式导航栏' },
  { stage: 1, day: 5, title: 'JavaScript 基础语法：变量、函数、条件语句', homework: '写一个计算BMI的脚本' },
  { stage: 1, day: 6, title: 'DOM操作：获取元素、修改内容、事件绑定', homework: '点击按钮改变文字颜色' },
  { stage: 1, day: 7, title: '综合练习：做一个带样式的待办事项列表（静态）', homework: '使用HTML+CSS+JS完成任务列表' },
  { stage: 1, day: 8, title: 'JavaScript 数组和对象', homework: '用数组管理多个任务' },
  { stage: 1, day: 9, title: 'localStorage 的使用', homework: '让任务列表支持本地保存' },
  { stage: 1, day: 10, title: '事件监听进阶（键盘事件、表单提交）', homework: '实现回车添加任务' },
  { stage: 1, day: 11, title: '函数封装、模块化思想', homework: '将功能模块化' },
  { stage: 1, day: 12, title: '异步编程概念（setTimeout/Promise）', homework: '模拟异步加载数据' },
  { stage: 1, day: 13, title: 'AJAX / Fetch API 基础', homework: '请求 JSONPlaceholder 获取用户信息' },
  { stage: 1, day: 14, title: '综合项目：天气查询页面（调用公开API）', homework: '显示城市天气信息' },
  
  // 第二阶段：C# 编程基础
  { stage: 2, day: 15, title: 'C# 开发环境搭建（Visual Studio 或 VS Code + .NET SDK）', homework: '输出 "Hello World"' },
  { stage: 2, day: 16, title: '变量、数据类型、运算符', homework: '计算两个数的加减乘除' },
  { stage: 2, day: 17, title: '条件语句 if-else、switch-case', homework: '判断成绩等级' },
  { stage: 2, day: 18, title: '循环语句 for/while/do-while', homework: '打印九九乘法表' },
  { stage: 2, day: 19, title: '数组与集合（List<T>）', homework: '输入一组数字并输出最大值' },
  { stage: 2, day: 20, title: '方法定义与调用', homework: '写一个判断素数的方法' },
  { stage: 2, day: 21, title: '面向对象基础：类、对象、属性、方法', homework: '定义 Person 类' },
  { stage: 2, day: 22, title: '构造函数、访问修饰符', homework: '初始化不同参数的对象' },
  { stage: 2, day: 23, title: '字符串处理、日期格式化', homework: '格式化当前日期' },
  { stage: 2, day: 24, title: '文件读写（File.ReadAllText/WriteAllText）', homework: '读写文本文件' },
  { stage: 2, day: 25, title: '异常处理 try-catch', homework: '处理除以零错误' },
  { stage: 2, day: 26, title: 'LINQ 查询基础', homework: '对集合进行筛选排序' },
  { stage: 2, day: 27, title: '异步编程 async/await', homework: '异步下载网页内容' },
  { stage: 2, day: 28, title: '综合练习：控制台通讯录管理系统', homework: '添加、删除、显示联系人' },
  
  // 第三阶段：前端框架（Vue.js）
  { stage: 3, day: 29, title: 'Vue.js 简介、创建第一个 Vue 应用', homework: '显示动态欢迎语' },
  { stage: 3, day: 30, title: '数据绑定、指令 v-text/v-html/v-model', homework: '实现双向绑定输入框' },
  { stage: 3, day: 31, title: '条件渲染 v-if/v-show', homework: '显示/隐藏内容' },
  { stage: 3, day: 32, title: '列表渲染 v-for', homework: '显示任务列表' },
  { stage: 3, day: 33, title: '事件绑定 v-on', homework: '点击按钮添加任务' },
  { stage: 3, day: 34, title: '组件化开发', homework: '创建可复用的任务组件' },
  { stage: 3, day: 35, title: '生命周期钩子 created/mounted', homework: '页面加载时请求数据' },
  { stage: 3, day: 36, title: 'Vue Router 基础', homework: '创建多页面应用' },
  { stage: 3, day: 37, title: 'Vuex 状态管理基础', homework: '全局共享计数器' },
  { stage: 3, day: 38, title: '综合项目：Todo List（Vue版）', homework: '支持添加、删除、持久化' },
  
  // 第四阶段：浏览器自动化 & CEF3
  { stage: 4, day: 39, title: '浏览器自动化简介、Selenium WebDriver 概述', homework: '安装 Selenium NuGet 包' },
  { stage: 4, day: 40, title: '使用 Selenium 打开浏览器、访问网页', homework: '自动打开百度首页' },
  { stage: 4, day: 41, title: '查找元素、点击、输入文本', homework: '自动搜索"你好"' },
  { stage: 4, day: 42, title: '处理弹窗、切换窗口、iframe', homework: '处理 alert 弹窗' },
  { stage: 4, day: 43, title: '等待机制（显式等待 vs 隐式等待）', homework: '等待元素出现再操作' },
  { stage: 4, day: 44, title: '截图、获取页面源码、执行 JS 脚本', homework: '截图并保存到文件' },
  { stage: 4, day: 45, title: 'CEF3 框架简介、CefSharp 在 C# 中的集成', homework: '创建 WinForms 窗体嵌入浏览器' },
  { stage: 4, day: 46, title: '加载网页、执行 JS、获取返回值', homework: '调用 JS 获取页面标题' },
  { stage: 4, day: 47, title: '注入 JS 脚本、模拟点击网页按钮', homework: '自动填写登录表单' },
  { stage: 4, day: 48, title: 'CEF3 与 C# 交互（绑定 JS 函数）', homework: 'JS 调用 C# 方法' },
  { stage: 4, day: 49, title: '使用 CEF3 实现自动化登录网站', homework: '登录某个测试网站' },
  { stage: 4, day: 50, title: '使用 CEF3 拦截网络请求（如获取 Ajax 返回数据）', homework: '获取网页中的 JSON 数据' },
  { stage: 4, day: 51, title: '封装自动化流程为类库或独立程序', homework: '提供一个自动化接口' },
  { stage: 4, day: 52, title: '项目实战：自动签到某网站（需配合账号）', homework: '完整流程自动化' },
  { stage: 4, day: 53, title: '错误处理、日志记录、异常捕获', homework: '增强程序健壮性' },
  { stage: 4, day: 54, title: '优化性能、打包发布', homework: '发布为.exe程序' }
];

// 初始化用户学习进度
const initializeProgress = async (req, res) => {
  try {
    const userId = req.user.id;

    // 检查是否已经初始化
    const existingProgress = await StudyProgress.findOne({
      where: { user_id: userId }
    });

    if (existingProgress) {
      return res.json({ message: '学习进度已存在' });
    }

    // 为用户创建完整的学习计划
    const progressData = studyPlanData.map(item => ({
      user_id: userId,
      day_number: item.day,
      stage: item.stage,
      title: item.title,
      homework_content: item.homework
    }));

    await StudyProgress.bulkCreate(progressData);

    res.json({ message: '学习进度初始化成功' });
  } catch (error) {
    console.error('初始化学习进度错误:', error);
    res.status(500).json({ message: '服务器内部错误' });
  }
};

// 获取用户学习进度
const getProgress = async (req, res) => {
  try {
    const userId = req.user.id;
    const { stage } = req.query;

    const whereCondition = { user_id: userId };
    if (stage) {
      whereCondition.stage = stage;
    }

    const progress = await StudyProgress.findAll({
      where: whereCondition,
      order: [['day_number', 'ASC']]
    });

    // 计算总体进度
    const totalTasks = await StudyProgress.count({ where: { user_id: userId } });
    const completedTasks = await StudyProgress.count({
      where: { user_id: userId, is_completed: true }
    });

    const overallProgress = totalTasks > 0 ? Math.round((completedTasks / totalTasks) * 100) : 0;

    // 各阶段进度
    const stageProgress = [];
    for (let i = 1; i <= 4; i++) {
      const stageTotal = await StudyProgress.count({
        where: { user_id: userId, stage: i }
      });
      const stageCompleted = await StudyProgress.count({
        where: { user_id: userId, stage: i, is_completed: true }
      });
      
      stageProgress.push({
        stage: i,
        total: stageTotal,
        completed: stageCompleted,
        percentage: stageTotal > 0 ? Math.round((stageCompleted / stageTotal) * 100) : 0
      });
    }

    res.json({
      progress,
      stats: {
        overallProgress,
        totalTasks,
        completedTasks,
        stageProgress
      }
    });
  } catch (error) {
    console.error('获取学习进度错误:', error);
    res.status(500).json({ message: '服务器内部错误' });
  }
};

// 更新学习进度
const updateProgress = async (req, res) => {
  try {
    const { dayNumber } = req.params;
    const { isCompleted, studyTimeMinutes, notes, homeworkStatus } = req.body;
    const userId = req.user.id;

    const progress = await StudyProgress.findOne({
      where: { user_id: userId, day_number: dayNumber }
    });

    if (!progress) {
      return res.status(404).json({ message: '学习进度记录不存在' });
    }

    const updateData = {};
    if (isCompleted !== undefined) {
      updateData.is_completed = isCompleted;
      if (isCompleted) {
        updateData.completed_at = new Date();
      }
    }
    if (studyTimeMinutes !== undefined) updateData.study_time_minutes = studyTimeMinutes;
    if (notes !== undefined) updateData.notes = notes;
    if (homeworkStatus !== undefined) updateData.homework_status = homeworkStatus;

    await progress.update(updateData);

    // 如果完成了学习，更新用户的总学习天数
    if (isCompleted && !progress.is_completed) {
      await User.increment('total_study_days', { where: { id: userId } });
    } else if (!isCompleted && progress.is_completed) {
      await User.decrement('total_study_days', { where: { id: userId } });
    }

    res.json({ message: '学习进度更新成功', progress });
  } catch (error) {
    console.error('更新学习进度错误:', error);
    res.status(500).json({ message: '服务器内部错误' });
  }
};

// 获取学习统计
const getStats = async (req, res) => {
  try {
    const userId = req.user.id;

    // 总体统计
    const totalTasks = await StudyProgress.count({ where: { user_id: userId } });
    const completedTasks = await StudyProgress.count({
      where: { user_id: userId, is_completed: true }
    });

    // 各阶段统计
    const stageStats = [];
    for (let i = 1; i <= 4; i++) {
      const stageTotal = await StudyProgress.count({
        where: { user_id: userId, stage: i }
      });
      const stageCompleted = await StudyProgress.count({
        where: { user_id: userId, stage: i, is_completed: true }
      });
      
      stageStats.push({
        stage: i,
        stageName: getStageNames()[i],
        total: stageTotal,
        completed: stageCompleted,
        percentage: stageTotal > 0 ? Math.round((stageCompleted / stageTotal) * 100) : 0
      });
    }

    // 最近学习记录
    const recentProgress = await StudyProgress.findAll({
      where: { 
        user_id: userId, 
        completed_at: { [Op.not]: null } 
      },
      order: [['completed_at', 'DESC']],
      limit: 5
    });

    res.json({
      totalTasks,
      completedTasks,
      overallProgress: totalTasks > 0 ? Math.round((completedTasks / totalTasks) * 100) : 0,
      stageStats,
      recentProgress
    });
  } catch (error) {
    console.error('获取学习统计错误:', error);
    res.status(500).json({ message: '服务器内部错误' });
  }
};

// 阶段名称映射
const getStageNames = () => ({
  1: 'Web 技术基础',
  2: 'C# 编程基础',
  3: '前端框架 Vue.js',
  4: '浏览器自动化 & CEF3'
});

module.exports = {
  initializeProgress,
  getProgress,
  updateProgress,
  getStats
}; 